package com.digua.iot.confignetwork

import android.app.Activity
import android.content.Context
import android.os.Bundle
import com.blankj.utilcode.util.CrashUtils
import com.blankj.utilcode.util.Utils
import com.digua.base.base.App
import com.digua.base.util.LogUtil
import com.digua.iot.confignetwork.config.Config
import com.uc.crashsdk.export.CrashApi
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import java.util.LinkedList
import kotlin.system.exitProcess

class MyApp : App() {

    private val mActivityList: MutableList<Activity> = LinkedList()
    private var context: Context? = null

    companion object {
        val instance: MyApp by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { Utils.getApp() as MyApp }
    }

    override fun onCreate() {
        super.onCreate()
        context = this
        initCrash()
        initUmeng()
        //ApiBase.init(ApiBean::class.java, "data")
        initData()
    }

    private fun initData() {
    }

    private fun initCrash() {
        try {
            CrashUtils.init { crashInfo: CrashUtils.CrashInfo -> LogUtil.e("异常拦截：$crashInfo") }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun initUmeng() {
        try {
            UMConfigure.preInit(this, Config.umengKey, "Umeng")
            UMConfigure.init(this, Config.umengKey, "Umeng", UMConfigure.DEVICE_TYPE_PHONE, "")
            UMConfigure.setLogEnabled(false)
            val customInfo = Bundle()
            customInfo.putBoolean("mCallNativeDefaultHandler", true)
            CrashApi.getInstance().updateCustomInfo(customInfo)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    // add Activity
    fun addActivity(activity: Activity) {
        mActivityList.add(activity)
    }

    fun exit() {
        try {
            mActivityList.map { it.finish() }
        } catch (e: Exception) {
            LogUtil.e("异常:", e)
        } finally {
            MobclickAgent.onKillProcess(this)
            exitProcess(0)
        }
    }

    fun colse(clz: Class<*>) {
        val tempArr1 = mActivityList.filter { it::class.java.simpleName == clz.simpleName }
        val activity: Activity = tempArr1.firstOrNull() ?: return
        if (!activity.isFinishing) activity.finish()
        mActivityList.remove(activity)
    }

    fun <T> finishAll(clz: Class<T>) {
        mActivityList.forEach {
            if (it::class.java.simpleName != clz.simpleName) {
                if (!it.isFinishing) it.finish()
            }
        }
        mActivityList.removeIf { it::class.java.simpleName != clz.simpleName }
    }
}
